<template>
  <div class="payment-page">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <div class="navbar-back" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div class="navbar-title">订单支付</div>
    </div>
    
    <!-- 支付金额 -->
    <div class="payment-amount">
      <div class="amount-label">支付金额</div>
      <div class="amount-value">¥{{ orderInfo.totalAmount }}</div>
    </div>
    
    <!-- 订单信息 -->
    <div class="order-info">
      <div class="info-title">订单信息</div>
      <div class="info-item">
        <span class="item-label">订单编号：</span>
        <span class="item-value">{{ orderInfo.orderNumber || '加载中...' }}</span>
      </div>
      <div class="info-item">
        <span class="item-label">商品名称：</span>
        <span class="item-value">{{ orderInfo.productName || '加载中...' }}</span>
      </div>
      <div class="info-item">
        <span class="item-label">商品规格：</span>
        <span class="item-value spec-badge">{{ orderInfo.productSpec || '默认规格' }}</span>
      </div>
      <div class="info-item">
        <span class="item-label">订单时间：</span>
        <span class="item-value">{{ formatDate(orderInfo.createTime) || '加载中...' }}</span>
      </div>
    </div>
    
    <!-- 支付方式 -->
    <div class="payment-methods">
      <div class="info-title">支付方式</div>
      <div class="payment-method-list">
        <div 
          v-for="method in paymentMethods" 
          :key="method.value"
          :class="['payment-method-item', { active: selectedPaymentMethod === method.value }]"
          @click="selectPaymentMethod(method.value)"
        >
          <div class="method-icon">
            <i :class="method.icon"></i>
          </div>
          <div class="method-info">
            <div class="method-name">{{ method.name }}</div>
            <div class="method-desc" v-if="method.description">{{ method.description }}</div>
          </div>
          <div class="method-checkbox">
            <div class="checkbox" :class="{ checked: selectedPaymentMethod === method.value }"></div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 确认支付按钮 -->
    <div class="pay-button-container">
      <button class="pay-button" @click="confirmPayment" :disabled="loading">
        {{ loading ? '处理中...' : '确认支付' }}
      </button>
    </div>

    <!-- 支付结果对话框 -->
    <van-dialog v-model="showPaymentResult" title="支付结果" :showConfirmButton="false">
      <div class="payment-result">
        <div v-if="paymentSuccess" class="result-icon success">
          <i class="fas fa-check-circle"></i>
        </div>
        <div v-else class="result-icon error">
          <i class="fas fa-times-circle"></i>
        </div>
        <div class="result-message">{{ paymentResultMessage }}</div>
        <div class="result-actions">
          <button class="action-button secondary" @click="goToOrders">查看订单</button>
          <button class="action-button primary" @click="goToHome">返回首页</button>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast, showDialog } from 'vant';
import api from '@/network/api';

export default defineComponent({
  name: 'PaymentView',
  
  setup() {
    const router = useRouter();
    const route = useRoute();
    const loading = ref(false);
    const orderInfo = ref({
      orderId: '',
      orderNumber: '',
      productName: '',
      totalAmount: '0.00',
      createTime: new Date()
    });
    
    // 支付方式
    const paymentMethods = [
      {
        name: '微信支付',
        value: 'wechat',
        icon: 'fab fa-weixin',
        description: '推荐使用微信扫码支付'
      },
      {
        name: '支付宝',
        value: 'alipay',
        icon: 'fab fa-alipay',
        description: '推荐有支付宝账户的用户使用'
      },
      {
        name: '银联支付',
        value: 'creditcard',
        icon: 'fa fa-credit-card',
        description: '支持大多数银行卡'
      }
    ];
    
    const selectedPaymentMethod = ref('wechat');
    const showPaymentResult = ref(false);
    const paymentSuccess = ref(false);
    const paymentResultMessage = ref('');
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    };
    
    // 从URL参数中获取支付方式
    const initPaymentMethod = () => {
      // 获取URL中的paymentMethod参数
      const paymentMethodParam = route.query.paymentMethod;
      if (paymentMethodParam) {
        console.log('从URL参数获取的支付方式:', paymentMethodParam);
        
        // 检查是否是有效的支付方式
        const isValidPaymentMethod = paymentMethods.some(method => method.value === paymentMethodParam);
        
        if (isValidPaymentMethod) {
          selectedPaymentMethod.value = paymentMethodParam;
          console.log('设置默认支付方式为:', selectedPaymentMethod.value);
        }
      }
    };
    
    // 返回上一页
    const goBack = () => {
      router.back();
    };
    
    // 选择支付方式
    const selectPaymentMethod = (method) => {
      selectedPaymentMethod.value = method;
    };
    
    // 获取订单信息
    const fetchOrderInfo = async () => {
      const orderId = route.query.orderId;
      if (!orderId) {
        showToast('订单参数错误');
        setTimeout(() => {
          router.replace('/orders');
        }, 1500);
        return;
      }
      
      try {
        loading.value = true;
        const response = await api.getOrderDetail(Number(orderId));
        console.log('获取订单详情:', response);
        if (response && response.code === 100 && response.data) {
          // 根据返回数据格式取出订单信息
          let orderData;
          if (Array.isArray(response.data)) {
            orderData = response.data.find(o => o.orderId === Number(orderId)) || response.data[0];
          } else {
            orderData = response.data;
          }

          // 获取商品规格信息
          let productSpec = '默认规格';
          
          // 尝试从不同地方获取规格信息
          if (orderData.orderItems && orderData.orderItems.length > 0) {
            // 从订单项中获取
            const firstItem = orderData.orderItems[0];
            productSpec = firstItem.specValue || firstItem.spec_value || firstItem.productVariant || 
                          firstItem.variant || firstItem.attributes || '默认规格';
          } else if (orderData.items) {
            // 从items字段获取
            productSpec = orderData.items.specValue || orderData.items.spec_value || 
                          orderData.items.variant || orderData.items.attributes || '默认规格';
          } else if (orderData.productsItems && orderData.productsItems.length > 0) {
            // 从productsItems中获取
            const firstProduct = orderData.productsItems[0];
            productSpec = firstProduct.specValue || firstProduct.spec_value || 
                          firstProduct.variant || firstProduct.attributes || '默认规格';
          }
          
          orderInfo.value = {
            orderId: orderData.orderId,
            orderNumber: orderData.orderNumber || `SO${orderData.orderId}`,
            totalAmount: orderData.totalAmount?.toFixed(2) || '0.00',
            createTime: orderData.createdAt || orderData.createTime || new Date(),
            productName: getProductName(orderData),
            productSpec: productSpec
          };
          
          console.log('订单信息:', orderInfo.value);
        } else {
          showToast('获取订单信息失败');
        }
      } catch (error) {
        console.error('获取订单详情失败:', error);
        showToast('获取订单信息失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 获取订单商品名称
    const getProductName = (orderData) => {
      // 根据接口返回的数据结构获取商品名称
      if (orderData.productsItems && orderData.productsItems.length > 0) {
        const firstProduct = orderData.productsItems[0];
        const restCount = orderData.productsItems.length - 1;
        return restCount > 0 
          ? `${firstProduct.name || '未命名商品'} 等${orderData.productsItems.length}件商品` 
          : (firstProduct.name || '未命名商品');
      } else if (orderData.orderItems && orderData.orderItems.length > 0) {
        const firstItem = orderData.orderItems[0];
        const restCount = orderData.orderItems.length - 1;
        return restCount > 0 
          ? `${firstItem.productName || '未命名商品'} 等${orderData.orderItems.length}件商品` 
          : (firstItem.productName || '未命名商品');
      } else {
        return '商品详情';
      }
    };
    
    // 确认支付
    const confirmPayment = async () => {
      if (loading.value) return;
      
      try {
        loading.value = true;
        
        // 准备订单支付数据，确保包含所有必要字段
        const orderPaymentData = {
          orderId: orderInfo.value.orderId,
          orderNumber: orderInfo.value.orderNumber,
          paymentMethod: selectedPaymentMethod.value, // 修改为后端实体类中的字段名
          totalAmount: orderInfo.value.totalAmount,
          status: 'pending_payment', // 添加当前订单状态
          // 添加额外可能需要的字段
          productName: orderInfo.value.productName,
          createTime: orderInfo.value.createTime,
          productSpec: orderInfo.value.productSpec
        };
        
        console.log('提交支付数据:', orderPaymentData);
        
        // 显示支付处理中状态
        showToast('支付处理中...');
        
        // 调用后端支付接口
        const response = await api.paymentOrder(orderPaymentData);
        console.log('支付接口返回:', response);
        
        // 处理支付结果
        if (response && response.code === 100) {
          // 支付成功
          paymentSuccess.value = true;
          paymentResultMessage.value = '支付成功！感谢您的购买。';
          
          // 显示支付结果对话框
          showPaymentResult.value = true;
          
          // 2秒后自动跳转到订单页面
          setTimeout(() => {
            showPaymentResult.value = false;
            router.replace('/orders?status=all');
          }, 2000);
        } else {
          // 支付失败
          paymentSuccess.value = false;
          paymentResultMessage.value = response?.message || '支付失败，请重试或选择其他支付方式。';
          
          // 显示支付结果对话框
          showPaymentResult.value = true;
        }
      } catch (error) {
        console.error('支付处理失败:', error);
        paymentSuccess.value = false;
        paymentResultMessage.value = '支付处理遇到问题，请稍后再试。';
        showPaymentResult.value = true;
      } finally {
        loading.value = false;
      }
    };
    
    // 查看订单
    const goToOrders = () => {
      showPaymentResult.value = false;
      router.replace('/orders?status=all'); // 跳转到全部订单页面
    };
    
    // 返回首页
    const goToHome = () => {
      showPaymentResult.value = false;
      router.replace('/home');
    };
    
    onMounted(() => {
      // 初始化默认支付方式
      initPaymentMethod();
      
      // 获取订单信息
      fetchOrderInfo();
    });
    
    return {
      loading,
      orderInfo,
      paymentMethods,
      selectedPaymentMethod,
      showPaymentResult,
      paymentSuccess,
      paymentResultMessage,
      formatDate,
      goBack,
      selectPaymentMethod,
      confirmPayment,
      goToOrders,
      goToHome
    };
  }
});
</script>

<style scoped>
.payment-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 80px;
}

.navbar {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 10;
}

.navbar-back {
  margin-right: 15px;
  cursor: pointer;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-weight: 500;
}

.payment-amount {
  background-color: white;
  padding: 20px;
  text-align: center;
  margin-bottom: 10px;
}

.amount-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

.amount-value {
  font-size: 36px;
  font-weight: bold;
  color: #303133;
}

.order-info, .payment-methods {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.info-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5;
}

.info-item:last-child {
  margin-bottom: 0;
}

.item-label {
  color: #606266;
  width: 80px;
  flex-shrink: 0;
}

.item-value {
  color: #303133;
  flex: 1;
}

.payment-method-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.payment-method-item {
  display: flex;
  padding: 15px;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
}

.payment-method-item:last-child {
  border-bottom: none;
}

.payment-method-item.active {
  background-color: #f0f9ff;
}

.method-icon {
  width: 40px;
  height: 40px;
  background-color: #f5f7fa;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  font-size: 20px;
}

.method-icon i.fab.fa-weixin {
  color: #07c160;
}

.method-icon i.fab.fa-alipay {
  color: #00a0e9;
}

.method-icon i.fa.fa-credit-card {
  color: #1677ff;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
  font-weight: 500;
}

.method-desc {
  font-size: 12px;
  color: #909399;
}

.method-checkbox {
  margin-left: 15px;
}

.checkbox {
  width: 20px;
  height: 20px;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  position: relative;
}

.checkbox.checked {
  border-color: #3490dc;
}

.checkbox.checked::after {
  content: "";
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #3490dc;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.pay-button-container {
  padding: 20px 15px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.pay-button {
  width: 100%;
  height: 44px;
  background-color: #ff6b00;
  color: white;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
}

.pay-button:disabled {
  background-color: #ffd8b8;
}

.payment-result {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.result-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.result-icon.success {
  color: #07c160;
}

.result-icon.error {
  color: #f56c6c;
}

.result-message {
  font-size: 16px;
  color: #303133;
  margin-bottom: 30px;
  text-align: center;
}

.result-actions {
  display: flex;
  justify-content: space-around;
  width: 100%;
}

.action-button {
  width: 45%;
  height: 40px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.action-button.primary {
  background-color: #3490dc;
  color: white;
  border: none;
}

.action-button.secondary {
  background-color: white;
  color: #3490dc;
  border: 1px solid #3490dc;
}

.spec-badge {
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  color: #0369a1;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 12px;
  display: inline-block;
}
</style> 